/*
 * 基于iview的UEditor组件
 * @Author: ljb
 * @Date: 2018-02-25 10:42:20
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-06-07 09:42:09
 */
<style lang="less" rel="stylesheet/less" type="text/less">

    .ue-preview-content {
        table {
            border-collapse: collapse;
        }
    }

</style>
<template>
	<div class="vue-ueditor">
		<script
			:id="random_id"
			:name="random_name"
			type="text/plain"/>
		<Button
			v-if="previewWidth"
			type="success"
			icon="eye"
			@click="preViewResult">
			{{ $t('ueditor.preview') }}
		</Button>
	</div>

</template>

<script>
export default {
	name: 'VueUEditor',
	props: {
		preData: {
			type: String,
		},
		previewWidth: {},
		ueditorPath: {
			// UEditor 代码的路径
			type: String,
			default: '/ueditor1_4_3_3/',
		},
		ueditorConfig: {
			// UEditor 配置项
			type: Object,
			default() {
				return {
					initialFrameWidth: 1200,
				};
			},
		},
	},
	data() {
		return {
			// 为了避免麻烦，每个编辑器实例都用不同的 id 和 name
			random_id: `editor_${new Date().getTime()}`,
			random_name: `content_${new Date().getTime()}`,
			instance: null,
			// scriptTagStatus -> 0:代码未加载，1:两个代码依赖加载了一个，2:两个代码依赖都已经加载完成
			scriptTagStatus: 0,
		};
	},
	watch: {

		preData() {
			if (!this.preData || !this.instance) return;

			let pre_content = '';

			if (!window.unescape) {
				const encoder = new TextEncoder();

				const dencoder = new TextDecoder();

				pre_content = dencoder.decode(encoder.encode(this.preData));
			} else {
				pre_content = unescape(escape(this.preData));
			}

			this.instance.setContent(pre_content);
		},

	},
	created() {
		if (window.UE !== undefined) {
			// 如果全局对象存在，说明编辑器代码已经初始化完成，直接加载编辑器
			this.scriptTagStatus = 3;
			this.initEditor();
		} else {
			// 如果全局对象不存在，说明编辑器代码还没有加载完成，需要加载编辑器代码
			this.insertScriptTag();
		}
	},
	beforeDestroy() {
		// 组件销毁的时候，要销毁 UEditor 实例
		if (this.instance !== null && this.instance.destroy) {
			this.instance.destroy();
		}
	},
	methods: {
		/**
         * 清空富文本编辑器的内容
         * @return {undefined}
         */
		clearContent() {
			this.instance.setContent('');
		},
		/**
         * 预览富文本编辑器的内容
         * @return {undefined}
         */
		preViewResult() {
			const config = {
				title: this.$t('ueditor.preview_content'), // '预览内容',
				render: h => h('div', {
					attrs: {
						class: 'ue-preview-content',
					},
					domProps: {
						innerHTML: this.instance.getContent(),
					},
				}),
				width: this.previewWidth,
			};

			this.$Modal.info(config);
		},
		/**
         * 动态加载ueditor所需js
         * @return {undefined}
         */
		insertScriptTag() {
			let editorScriptTag = document.getElementById('editorScriptTag');
			let configScriptTag = document.getElementById('configScriptTag');
			let parseScriptTag = document.getElementById('parseScriptTag');

			// 如果这个tag不存在，则生成相关代码tag以加载代码
			if (editorScriptTag === null) {
				configScriptTag = document.createElement('script');
				configScriptTag.type = 'text/javascript';
				configScriptTag.src = `${this.ueditorPath}ueditor.config.js`;
				configScriptTag.id = 'configScriptTag';

				editorScriptTag = document.createElement('script');
				editorScriptTag.type = 'text/javascript';
				editorScriptTag.src = `${this.ueditorPath}ueditor.all.js`;
				editorScriptTag.id = 'editorScriptTag';

				parseScriptTag = document.createElement('script');
				parseScriptTag.type = 'text/javascript';
				parseScriptTag.src = `${this.ueditorPath}ueditor.parse.js`;
				parseScriptTag.id = 'parseScriptTag';

				const s = document.getElementsByTagName('head')[0];
				s.appendChild(configScriptTag);
				s.appendChild(editorScriptTag);
				s.appendChild(parseScriptTag);
			}

			// 等待代码加载完成后初始化编辑器
			if (configScriptTag.loaded) {
				this.scriptTagStatus++;
			} else {
				configScriptTag.addEventListener('load', () => {
					this.scriptTagStatus++;
					configScriptTag.loaded = true;
					this.initEditor();
				});
			}

			if (editorScriptTag.loaded) {
				this.scriptTagStatus++;
			} else {
				editorScriptTag.addEventListener('load', () => {
					this.scriptTagStatus++;
					editorScriptTag.loaded = true;
					this.initEditor();
				});
			}

			if (parseScriptTag.loaded) {
				this.scriptTagStatus++;
			} else {
				parseScriptTag.addEventListener('load', () => {
					this.scriptTagStatus++;
					parseScriptTag.loaded = true;
					this.initEditor();
				});
			}

			this.initEditor();
		},
		/**
         * 初始化编辑器
         * @return {undefined}
         */
		initEditor() {
			// scriptTagStatus 为 3 的时候，说明两个需引入的 js 文件都已经被引入，且加载完成
			if (this.scriptTagStatus === 3 && this.instance === null) {
				// Vue 异步执行 DOM 更新，这样一来代码执行到这里的时候可能 template 里面的 script 标签还没真正创建
				// 所以，我们只能在 nextTick 里面初始化 UEditor
				this.$nextTick(() => {
					this.instance = window.UE.getEditor(this.random_id, this.ueditorConfig);
					// 绑定事件，当 UEditor 初始化完成后，将编辑器实例通过自定义的 ready 事件交出去
					// this.instance.addListener('ready', () => {
					//     this.$emit('ready', this.instance);
					// });
					// this.instance.addListener("beforeInsertImage", () => {
					//     console.log('上传图片');
					// });
					// this.instance.addListener('afterinsertimage', () => {
					//     console.log('插入图片');
					// });
					this.instance.addListener('contentChange', () => {
						this.$emit('change', this.instance.getContent());
					});
				});
			}
		},
	},
};
</script>
